import React, { useImperativeHandle, forwardRef } from "react";
import AdminModal from "../AdminModal/index.tsx";
import { Form } from "antd";
import ModalForm from "../ModalForm/index.tsx";
import { FormItemConfigs } from "../../global.ts";
interface AddModalProps {
  formItemConfigs?: FormItemConfigs[];
  onOk?: (data: any, callback: () => void) => void;
  modalFormNode?: React.ReactElement<typeof ModalForm>;
  modalWidth?: number;
}

export interface AddModalHandles {
  show: (data: any) => void;
}

const AddModal = forwardRef<AddModalHandles, AddModalProps>(
  ({ formItemConfigs, onOk, modalFormNode,modalWidth }, ref) => {
    const [showModal, setShowModal] = React.useState(false);
    const [form] = Form.useForm();

    useImperativeHandle(ref, () => ({
      show: (data: any) => {
        setShowModal(true);
      },
    }));

    const handleOk = () => {
      form.submit();
    };

    const handleSubmit = (values: any) => {
      onOk?.(values, () => {
        setShowModal(false);
        form.resetFields();
      });
    };

    const handleCancel = () => {
      setShowModal(false);
      form.resetFields();
    };

    return (
      <AdminModal
        isVisible={showModal}
        title="新增"
        onCancel={() => handleCancel()}
        onOk={() => handleOk()}
        modalWidth={modalWidth}
      >
        {/* <Form form={form} onFinish={handleSubmit}>
          <FormItems formItemsConfigs={formItemConfigs} />
        </Form> */}

        {React.isValidElement(modalFormNode) ? (
          React.cloneElement(modalFormNode as any, {
            form,
            onFinish: handleSubmit,
          })
        ) : (
          <ModalForm
            form={form}
            onFinish={handleSubmit}
            formItemConfigs={formItemConfigs}
          />
        )}
      </AdminModal>
    );
  }
);

export default AddModal;
